package com.tompai.ftpan.web.controller;

import java.io.EOFException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tompai.ftpan.web.config.Constants;
import com.tompai.ftpan.web.dto.MergeFileDto;
import com.tompai.ftpan.web.dto.ResponseDto;
import com.tompai.ftpan.web.entity.ResourceChunk;
import com.tompai.ftpan.web.service.ResourceService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author tompai
 * @date 2020-01-27
 */
@Slf4j
@RestController
@RequestMapping(Constants.API_VERSION)
public class ResourceController {

	private final ResourceService resourceService;

	@Autowired
	public ResourceController(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	@GetMapping("/resource/chunk")
	public ResponseEntity<ResponseDto> checkChunk(ResourceChunk chunk) {

		if (resourceService.checkChunk(chunk)) {
			return ResponseEntity.ok(ResponseDto.success("该文件块已经上传"));
		}
		return ResponseEntity.status(HttpStatus.NOT_MODIFIED).body(ResponseDto.success());
	}

	@PostMapping("/resource/chunk")
	public ResponseEntity<ResponseDto> uploadChunk(ResourceChunk chunk) {

		resourceService.saveChunk(chunk);
		return ResponseEntity.ok(ResponseDto.success());
	}

	@PostMapping("/resource/merge")
	public ResponseEntity<ResponseDto> mergeResource(@RequestBody MergeFileDto fileDto) {

		resourceService.mergeChunk(fileDto);
		return ResponseEntity.ok(ResponseDto.success());
	}

	@ExceptionHandler
	public void eofException(EOFException e) {
		log.warn("ftpan exception");
	}
}
